package cn.iocoder.yudao.module.infra.tts.impl.selfbuilt;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.infra.okhttp.OkHttpUtils;
import cn.iocoder.yudao.module.infra.tts.TTSConfig;
import cn.iocoder.yudao.module.infra.tts.impl.SimpleTTSApi;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文本转音频（使用 OkHttp 实现）
 */
@Service("tts-self-built")
@Slf4j
public class SelfBuiltTTSApiImpl extends SimpleTTSApi {
    private TTSConfig.Config selfBuiltConfig;

    @Resource
    private TTSConfig ttsConfig;

    @PostConstruct
    public void init() {
        selfBuiltConfig = ttsConfig.getService("self-built");
    }

    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    @Override
    public byte[] convertTextToSpeech(String voice, String voice_path, String voice_hash, String voice_suffix, String response_format, String input) {
        final String apiUrl = selfBuiltConfig.getApiUrl();

        return post(voice, voice_path, voice_hash, voice_suffix, response_format, input, apiUrl);
    }

    @NotNull
    private static byte[] post(String voice, String voice_path, String voice_hash, String voice_suffix, String response_format, String input, String apiUrl) {
        final Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("voice", voice);
        bodyMap.put("response_format", response_format);
        bodyMap.put("input", input);
        bodyMap.put("voice_path", voice_path);
        bodyMap.put("voice_hash", voice_hash);
        bodyMap.put("voice_suffix", voice_suffix);
        final String body = JsonUtils.toJsonString(bodyMap);

        log.info("文本转语音开始, body = {}", body);
        Request request = new Request.Builder()
                .url(apiUrl)
                .post(RequestBody.create(body, JSON_MEDIA_TYPE))
                .build();

        try (Response response = OkHttpUtils.getTtsClient().newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                byte[] audioData = response.body().bytes();
                log.info("文本转语音完成, audioData.len = {}, input = {}", audioData.length, input);
                return audioData;
            } else {
                final String responseBody = response.body() != null ? response.body().string() : "无响应内容";
                log.error("文本转语音失败, code = {}, body = {}", response.code(), responseBody);
                throw new RuntimeException(StrUtil.format("文本转语音失败, code = {}, body = {}", response.code(), responseBody));
            }
        } catch (IOException e) {
            throw new RuntimeException("文本转语音请求异常", e);
        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 2; i++) {
            new Thread() {

                @Override
                public void run() {
                    super.run();
                    String apiUrl = "https://317w7246e5.vicp.fun/v1/audio/speech";
                    String voice = null;
                    String response_format = "wav";
                    String input = "你是谁";
                    post(voice, null, null, null, response_format, input, apiUrl);
                }
            }.start();
        }

        Thread.sleep(1000 * 1200);
    }

}
